package com.network.chatsoft.controller;

import cn.hutool.http.HttpResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.network.chatsoft.entity.FileEntity;
import com.network.chatsoft.service.FileService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
public class FileController {

    @Value("${file.path}")
    String path;

    @Autowired
    FileService fileService;

    @PostMapping("/upload")
    public String fileUpload(MultipartFile file, @RequestParam("receiver") String[] receiver , HttpSession session) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String suffix=originalFilename.substring(originalFilename.lastIndexOf('.'));
        File dir=new File(path);
        if(!dir.exists()) dir.mkdirs();
        String url=UUID.randomUUID().toString();
        url=path+url+suffix;
        try {
            file.transferTo(new File(url));
            List<FileEntity> list=new ArrayList<>();
            for(int i=0;i<receiver.length;i++){
                FileEntity fileEntity=new FileEntity();
                fileEntity.setFileName(originalFilename);
                fileEntity.setReceiverName(receiver[i]);
                fileEntity.setUrl(url);
                fileEntity.setSenderName((String) session.getAttribute("username"));
                list.add(fileEntity);
            }
            fileService.saveBatch(list);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    @GetMapping("/fileList")
    public List<FileEntity> fileList(HttpSession session){
        String name= (String) session.getAttribute("username");
        LambdaQueryWrapper<FileEntity> qw=new LambdaQueryWrapper<>();
        qw.eq(Strings.isNotEmpty(name),FileEntity::getReceiverName,name);
        List<FileEntity> list = fileService.list(qw);
        return list;
    }

    @GetMapping("/download")
    public void download(String url, HttpServletResponse response) throws IOException {
        File file = new File(url);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer,0,len);
            }
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            inputStream.close();
            outputStream.close();
        }
    }
}
